package com.sample.service.impls;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sample.dto.GoodsDTO;
import com.sample.dto.OrderDTO;
import com.sample.dto.UserDTO;
import com.sample.entity.Order;
import com.sample.enums.OrderState;
import com.sample.mapper.OrderMapper;
import com.sample.service.GoodsService;
import com.sample.service.OrderService;
import com.sample.service.UserService;
import com.swak.annotation.FluxService;
import com.swak.annotation.ReliableMsg;
import com.swak.service.BaseService;
import com.swak.utils.BigDecimalUtils;
import com.swak.utils.StringUtils;

/**
 * 描述
 * 
 * @author Auto Generator
 * @date 2022-04-21T20:47:07.509267200
 */
@FluxService
@Service("swakOrderService")
public class OrderServiceImpl extends BaseService<Order, Long> implements OrderService {

	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private UserService userService;

	@Override
	@Transactional
	@ReliableMsg(queue = "Order_queue")
	public OrderDTO book(OrderDTO order) {

		/*
		 * 锁定库存
		 */
		GoodsDTO goods = goodsService
				.book(GoodsDTO.of().setQuantity(order.getGoodsQuantity()).setId(order.getGoodsId()));

		/*
		 * 计算订单金额
		 */
		order.setAmount(BigDecimalUtils.mul(goods.getPrice(), BigDecimal.valueOf(order.getGoodsQuantity())));

		/*
		 * 锁定账户
		 */
		UserDTO user = userService.book(UserDTO.of().setAccount(order.getAmount()).setId(order.getUserId()));

		/*
		 * 下单
		 */
		Order bookOrder = order.transform().setName(StringUtils.format("%s购买%s", user.getName(), goods.getName()))
				.setUserId(user.getId()).setUserName(user.getName()).setGoodsId(goods.getId())
				.setGoodsName(goods.getName()).setState(OrderState.Book.getType()).insert();

		/*
		 * 返回数据
		 */
		return OrderDTO.convert(orderMapper.get(bookOrder.getId()));
	}

	@Override
	@Transactional
	public void complete(OrderDTO order) {
		System.out.println("Order:" + order.getId());
		Order.of().setState(OrderState.Payed.getType()).setId(order.getId()).updateSelective();
	}
}
